module divide(	input sysclk,
		input reset,
		input [15:0] dividend,
		input [15:0] divider,
		input isNeg1,
		input isNeg2,
		input [2:0] enable,
		input done,
		output reg suc,
		output isNeg,
		output [15:0] quotient,
		output [15:0] reminder,
		output [31:0] so_diff,
		output [31:0] so_temp);

reg [4:0] count;
reg [16:0] s;
reg [31:0] temp;
reg [31:0] diff;
reg [1:0] state;
reg [1:0] nstate;
parameter s_init = 2'b00, s_shift = 2'b01, s_finish = 2'b10;

always @(*) begin
	state = nstate;
end

initial begin
	count <= 5'b0;
	suc <= 1'b0;
	s <=17'b0;
	diff <= 32'd0;
	temp <= 32'd0;
	nstate <= s_init;
end


always @(posedge sysclk ) begin
	if(reset) begin
		nstate <= s_init;
		count <= 5'b0;
		s <= 17'd0;
		temp <= 32'd0;
		diff = 32'd0;
		suc <= 1'b0;
		end
	else begin
		case (state)
			s_init: begin
							if (enable==3'b101) begin
									s <= divider[15]?{1'b1,divider}:{1'b1,~divider+1'b1};
									temp <= dividend[15]?{16'd0,~dividend+1'b1}:{16'd0,dividend};
									diff = 32'b0;
									nstate <= s_shift;
									end
							else nstate <= s_init;
						end
			s_shift:begin
				if (count < 5'd16) begin
			  		diff = temp +{s,15'b0};
					if (diff[31]==1'b1) begin  
						temp <= {temp[30:0],1'b0}; 
						end
					else begin 
						temp <= {diff[30:0],1'b1}; 
						end
					count <= count +1'b1;
					nstate <= s_shift;
			  		end
				else begin
					suc <= 1'b1;
					nstate <= s_finish;
					end
				end
			s_finish: begin
							if (done) begin
								suc <= 1'b0;
								count <= 5'd0;
								nstate <= s_init;
								end
							else nstate <= s_finish;
						end
		endcase
	end
end

assign quotient =temp[15:0];
assign isNeg = isNeg1^isNeg2;
assign so_diff = diff;
assign so_temp = temp;

endmodule
